package com.tyao.note.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 * 
 * @author Ty-user1
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * 执行handler之前拦截
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取session对象
		HttpSession session = request.getSession();
		// 获取用户对象
		Object obj = session.getAttribute("user");
		// 如果用户是未登录状态，执行拦截命令
		if (obj == null) {
			String path = request.getContextPath() + "/note/login";
			// 重定向到登录页面
			response.sendRedirect(path);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
